// src-electron/main.js
const { app, BrowserWindow, Tray, Menu, ipcMain } = require("electron/main");
const path = require("path");
const iconPath = path.join(__dirname, "../assets/tool.png");

let tray,
  mainWindow = null;

// 屏蔽安全警告
// ectron Security Warning (Insecure Content-Security-Policy)
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

// 创建浏览器窗口时，调用这个函数。
const createWindow = () => {
  mainWindow = new BrowserWindow({
    width: 1400,
    height: 800,
    icon: iconPath,
    title: "ToolDesk",
    frame: false,
    webPreferences: {
      backgroundThrottling: false, //设置应用在后台正常运行
      nodeIntegration: true, //设置能在页面使用nodejs的API
      contextIsolation: false,
    },
  });
  // development模式
  if (process.env.VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL);
    // 开启调试台
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(join(__dirname, "../../dist/index.html"));
  }
};
const setTrayConfig = () => {
  tray = new Tray(iconPath); //实例化一个tray对象，构造函数的唯一参数是需要在托盘中显示的图标url

  tray.setToolTip("ToolDesk"); //鼠标移到托盘中应用程序的图标上时，显示的文本

  tray.on("click", () => {
    //点击图标的响应事件，这里是切换主窗口的显示和隐藏
    if (mainWindow.isVisible()) {
      mainWindow.hide();
    } else {
      mainWindow.show();
    }
  });

  tray.on("right-click", () => {
    //右键点击图标时，出现的菜单，通过Menu.buildFromTemplate定制，这里只包含退出程序的选项。
    const menuConfig = Menu.buildFromTemplate([
      {
        label: "Quit",
        click: () => app.quit(),
      },
    ]);
    tray.popUpContextMenu(menuConfig);
  });
};

// Electron 会在初始化后并准备
app.whenReady().then(() => {
  createWindow();
  setTrayConfig();

  mainWindow.on("maximize", () => {
    mainWindow.webContents.send("mainWindow:opreate", true);
  });
  mainWindow.on("unmaximize", () => {
    mainWindow.webContents.send("mainWindow:opreate", false);
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
    tray = null;
    mainWindow = null;
  }
});

ipcMain.on("mainWindow:opreate", (_, arg) => {
  const map = {
    close: () => {
      app.quit();
    },
    max: () => {
      // setFullScreen(boolean)会直接全屏,没有从当前宽高过渡到全屏的过程
      mainWindow.maximize();
    },
    shrink: () => {
      mainWindow.restore();
    },
    min: () => {
      mainWindow.minimize();
    },
    tray: () => {
      mainWindow.hide();
    },
  };
  map[arg] && map[arg]();
});
